import requests,json

from db import db
from views.base import BaseHandler
from utils.comm import gettoken
class Openbank(BaseHandler):
    def get(self):
        status = self.get_query_argument("status")
        id = self.get_query_argument("id")
        if not all([status,id]):
            return self.finish({"code": 400, "msg": "字段不能为空"})
        sql = "update open_bank set status=%d  where id=%d"%(int(status),int(id))
        db.add(sql)
        db.commit()
        self.redirect("http://localhost:8080/updatebank")
    def post(self):
        # 从vue页面获取用户输入
        data = json.loads(self.request.body)
        userid = data["userid"]
        username = data["name"]
        image_url = data["url"]
        code = data["value"]
        bank_code = data["bank_code"]
        mobile = data["mobile"]
        pay_password = data["pay_password"]
        pwd = data["pwd"]
        if pwd!= pay_password:
            return self.finish({"code": 400, "msg": "两次密码输入不一致"})
        # 验证
        if not all([username,image_url,code,bank_code,mobile,pay_password]):
            return self.finish({"code": 400, "msg":"字段不能为空"})
        # sqls = "select * from open_bank where userid=%d" % (int(userid))
        # if sqls:
        #     return self.finish({"code": 400, "msg": "当前用户已开户"})
        # 写入开户表
        sql = "insert into open_bank(userid, image_url, code, username, bank_code, mobile, pay_password) values (%d,'%s','%s','%s','%s','%s','%s')"%(int(userid),image_url,code,username,bank_code,mobile,pay_password)
        id=db.add(sql)
        db.commit()
        # 查询redis中token是否存在，key：banktoken  value：token
        # 如果不存在调用flask登录接口，用户名和密码，获取token，存入redis
        # 如果存在调用flask众多的open_bank接口，传递的参数是开户表
        # ret = {"name":username,"url":image_url,"code":code,"bank_code":bank_code,"mobile":mobile}
        token = gettoken()
        token = str(token)
        redirect_url = "http://localhost:8000/Openbank"
        url = "http://localhost:5000/open_bank?id=%d&code=%s&username=%s&bank_code=%s&mobile=%s&url=%s&token=%s&redirect_url=%s&userid=%d"%(int(id),code,username,bank_code,mobile,image_url,token,redirect_url,int(userid))
        return self.finish({"code":200,"url":url})

class getaggrement(BaseHandler):
    def get(self):
        sql = "select * from aggrement where type=1"
        res = db.findAll(sql)
        return self.finish({"code": 200,"data":res})

class getaggr(BaseHandler):
    def get(self):
        id = self.get_query_argument("x")
        sql = "select * from aggrement where id=%d"%int(id)
        res = db.findAll(sql)
        return self.finish({"code": 200,"data":res})
